/**
 * Chrowety
 * bg/alerts.js
*/

var
alerts = {};

alerts.init = function( type, name )
{
	if( cfg.get('alerts.enabled') )
	{		
		var 
		tweets = tweet.get(type, name, {total: cfg.get('alerts.max') } );
		tweets = tweets['result'],
		n = tweets.length;
		
		if( n > 1 )
		{
			while( n-- )
				this.show( layout.alert(tweets[n], type, name) );
		}
	}
};

alerts.create = function( type, name, obj )
{
	if( !type || !name || !obj )
		return false;
	 
	if( cfg.get('alerts.enabled') )
	{
		var 
		render,
		tweets = isArray( obj ) ? obj : [obj],
		n = tweets.length;
		
		if( type === 'search')
			render = layout.search;
		else if ( type === 'default' && name === 'messages')
			render = layout.dm;
		else
			render = layout.tweet;
		
		if( n > 1 )
		{
			while( n-- )
				this.show( render( type, name, tweets[n], true ) );
		}
	}
};

alerts.autoSwitch = function()
{
	cfg.save('alerts.enabled', !cfg.get('alerts.enabled') );
};

alerts.show = function( data )
{
    var
    tweet = escape(data),
    html = chrome.extension.getURL('alerta.html'),
    notf = webkitNotifications.createHTMLNotification(html+'#'+tweet);
    notf.show();
};

alerts.closeAll = function()
{
	chrome.extension.getViews({type: 'notification'}).forEach(function( notf ){
		notf.close();
	});		
};